package com.gz.mylife.app;

import java.io.File;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import com.gz.mylife.Define;
import com.gz.mylife.R;
import com.gz.mylife.util.DialogUtils;
import com.gz.mylife.util.ImageUtils;
import com.gz.mylife.util.ToastUtils;
import com.gz.mylife.widget.OfflineDialog;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.zl.smartmall.library.ISmartMall;
import com.zl.smartmall.library.listener.SubmitApplyExchangeListener;
import com.zl.smartmall.library.listener.UploadApplyExchangePictureListener;
import com.zl.smartmall.library.po.OrderCommoditiesInfo;
import com.zl.smartmall.library.util.Constants;
import com.zl.smartmall.library.util.CrashHandler;
import com.zl.smartmall.library.util.Tools;


import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class ApplyExchange extends BaseActivity implements OnClickListener {

	private static final String TAG = ApplyExchange.class.getSimpleName();
	private static final int EXCHANGE_TYPE_RETURN_PRODUCT = 1;
	private static final int EXCHANGE_TYPE_EXCHANGE_PRODUCT = 2;
	
	private int mExchangeType = EXCHANGE_TYPE_EXCHANGE_PRODUCT;
	private int mCurrentQueuePosition;
	private String mImgCapturePath;
	private String mImgTempCachePath;
	private StringBuilder mSBuilder;
	private LayoutInflater mInflater;
	private List<Integer> mProductIds;
	private List<String> mPhotoPaths;
//	private OrderDetailInfo mOrderDetailInfo;
	private JSONObject mOrderDetailInfo;
	private UploadApplyExchangePictureListener mUploadApplyExchangePictureListener;
	private SubmitApplyExchangeListener mSubmitApplyExchangeListener;
	private List<OrderCommoditiesInfo> mOrderCommoditiesInfos;
	
	private EditText mEtReason;
	private LinearLayout mProductItemLayout;
	private LinearLayout mPictureThumbLayout;
	private TextView mTvExchangeType;
	private TextView mTvStatus;
	private TextView mTvOrderCode;
	private TextView mTvNickname;
	private TextView mTvPrice;
	private View mExchangeTypeSelectLayout;
	private ProgressDialog mProgressDialog;
	private OfflineDialog mOfflineDialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_apply_exchange);
		
		mInflater = getLayoutInflater();
		mOrderCommoditiesInfos = new ArrayList<OrderCommoditiesInfo>();
		mProductIds = new ArrayList<Integer>();
		mPhotoPaths = new ArrayList<String>();
		mSBuilder = new StringBuilder();
		mImgCapturePath = mImgTempCachePath = Tools.obtainDirPath(getApplicationContext(), Constants.FOLDER_IMG_TEMP_CACHE);

		setActionbarTitle("退换货申请", false);
		mPictureThumbLayout = (LinearLayout) findViewById(R.id.layout_picture_thumb);
		mProductItemLayout = (LinearLayout) findViewById(R.id.layout_product_item);
		mEtReason = (EditText) findViewById(R.id.et_reason);
		mExchangeTypeSelectLayout = findViewById(R.id.layout_exchange_type_select);
		mTvExchangeType = (TextView) findViewById(R.id.tv_exchange_type);
		mTvStatus = (TextView) findViewById(R.id.tv_status);
		mTvNickname = (TextView) findViewById(R.id.tv_receiver_name);
		mTvOrderCode = (TextView) findViewById(R.id.tv_order_code);
		mTvPrice = (TextView) findViewById(R.id.tv_price_sum);
		mOfflineDialog = (OfflineDialog) mInflater.inflate(R.layout.offline_dialog, null);
		findViewById(R.id.btn_submit).setOnClickListener(this);
		findViewById(R.id.layout_exchange_type).setOnClickListener(this);
		findViewById(R.id.tv_return_product).setOnClickListener(this);
		findViewById(R.id.tv_exchange_product).setOnClickListener(this);
		findViewById(R.id.layout_add_photo).setOnClickListener(this);

		int orderStatus = -1;
		try {
			mOrderDetailInfo = new JSONObject(getIntent().getStringExtra("order"));
			mTvNickname.setText("收货人：" + mOrderDetailInfo.getString("receiver"));
			mTvPrice.setText("订单号：" + mOrderDetailInfo.getString("orderCode"));
			mTvPrice.setText("￥" + new DecimalFormat("0.00").format(mOrderDetailInfo.getDouble("money")));
			orderStatus = mOrderDetailInfo.getInt("orderStatus");
			mOrderCommoditiesInfos.addAll(OrderCommoditiesInfo.parse(mOrderDetailInfo.getJSONArray("product")));
			
		}catch(JSONException e) {
			CrashHandler.e(e);
		}
		
		switch (orderStatus) {
		case Define.ORDER_STATUS_NO_PAY:
			mTvStatus.setText(Define.ORDER_STATUS_NO_PAY_TEXT);
			mTvStatus.setTextColor(getResources().getColor(R.color.text_color_my_order_no_pay));
			mTvStatus.setBackgroundResource(R.drawable.bg_my_orders_frame_red);
			break;
			
		case Define.ORDER_STATUS_PAID:
			mTvStatus.setText(Define.ORDER_STATUS_PAID_TEXT);
			mTvStatus.setTextColor(getResources().getColor(R.color.text_color_my_order_payed));
			mTvStatus.setBackgroundResource(R.drawable.bg_my_orders_frame_green);
			break;
			
		case Define.ORDER_STATUS_DELIVERIED:
			mTvStatus.setText(Define.ORDER_STATUS_DELIVERIED_TEXT);
			mTvStatus.setTextColor(getResources().getColor(R.color.text_color_my_order_payed));
			mTvStatus.setBackgroundResource(R.drawable.bg_my_orders_frame_green);
			break;
			
		case Define.ORDER_STATUS_SIGN_IN:
			mTvStatus.setText(Define.ORDER_STATUS_SIGN_IN_TEXT);
			mTvStatus.setTextColor(getResources().getColor(R.color.text_color_my_order_trade_successful));
			mTvStatus.setBackgroundResource(R.drawable.bg_my_orders_frame_orange);
			break;
			
		case Define.ORDER_STATUS_INVALIDATE:
			mTvStatus.setText(Define.ORDER_STATUS_INVALIDATE_TEXT);
			mTvStatus.setTextColor(getResources().getColor(R.color.RGB_A8A8A8));
			mTvStatus.setBackgroundResource(R.drawable.bg_my_orders_frame_gray);
			break;
			
		case Define.ORDER_STATUS_CANCEL:
			mTvStatus.setText(Define.ORDER_STATUS_CANCEL_TEXT);
			mTvStatus.setTextColor(getResources().getColor(R.color.RGB_A8A8A8));
			mTvStatus.setBackgroundResource(R.drawable.bg_my_orders_frame_gray);
			break;

		default:
			break;
		}
		
		initHandler();
		initProductItemLayout();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		return true;
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.iv_check:
			changeCheckStatus(v);
			break;
			
		case R.id.btn_submit:
			CrashHandler.d(TAG, "退货类型" + mExchangeType);

//			if(mProgressDialog == null) {
//				mProgressDialog = DialogUtils.showProgressDialog(
//						this, null, "申请提交中, 请稍等", true, false, null);
//			}else {
//				mProgressDialog.show();
//			}
//			if(mPhotoPaths.size() > 0) {
//				uploadPicture();
//				for(String path : mPhotoPaths) {
//					CrashHandler.d(TAG, path);
//				}
//			}else {
				submit();
//			}
			break;
			
		case R.id.layout_exchange_type:
			if(mExchangeTypeSelectLayout.getVisibility() == View.VISIBLE) {
				mExchangeTypeSelectLayout.setVisibility(View.GONE);
			}else {
				mExchangeTypeSelectLayout.setVisibility(View.VISIBLE);
			}
			
			break;
			
		case R.id.tv_exchange_product:
			mTvExchangeType.setText(((TextView) v).getText());
			mExchangeTypeSelectLayout.setVisibility(View.GONE);
			mExchangeType = EXCHANGE_TYPE_EXCHANGE_PRODUCT;
			break;
			
		case R.id.tv_return_product:
			mTvExchangeType.setText(((TextView) v).getText());
			mExchangeTypeSelectLayout.setVisibility(View.GONE);
			mExchangeType = EXCHANGE_TYPE_RETURN_PRODUCT;
			break;
			
		case R.id.layout_apply_exchange_item:
			changeCheckStatus((View) v.getTag());
			break;

		case R.id.layout_add_photo:
			if(mPhotoPaths.size() < 3) {
				Tools.hideInputBoard(this);
				takePhoto();
			}
			break;
			
		case R.id.iv_trashcan:
			mPictureThumbLayout.removeView((View) v.getParent());
			mPhotoPaths.remove(v.getTag());
			break;
		}
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if(keyCode == KeyEvent.KEYCODE_BACK) {
			if(mExchangeTypeSelectLayout.getVisibility() == View.VISIBLE) {
				mExchangeTypeSelectLayout.setVisibility(View.GONE);
			}else {
				finish();
			}
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case Define.ACTIVITY_CODE_PICTURE_FROM_CAMERA:
			if (resultCode == RESULT_OK) {
				Bitmap bitmap = null;
				try {
					Tools.saveBitmapAndGetPath(this, mImgCapturePath);
					if (mImgCapturePath != null) {
						BitmapFactory.Options opt = new BitmapFactory.Options();
						opt.inJustDecodeBounds = true;
						bitmap = BitmapFactory.decodeFile(
								mImgCapturePath, opt);
						bitmap = ImageUtils.compressBitmap(mImgCapturePath, Tools.getFitSample1(opt.outWidth, opt.outHeight, 
										Tools.dip2px(getApplicationContext(), 68), Tools.dip2px(getApplicationContext(), 68)));
						if (bitmap != null && !bitmap.isRecycled()) {
							refreshPhotoLayout(bitmap);
						}
					}
					
				} catch (Exception e) {
					CrashHandler.e(e);

				}finally {
//					if(bitmap != null && !bitmap.isRecycled()){
//						CrashHandler.d(TAG, "缩略图高" + bitmap.getHeight());
//					}
				}
			}
			break;
		}
	}

	private void refreshPhotoLayout(Bitmap bitmap) {
		// TODO Auto-generated method stub
		View v = mInflater.inflate(R.layout.apply_exchange_picture_thumb, mPictureThumbLayout, false);
		((LinearLayout.LayoutParams) v.getLayoutParams()).rightMargin = Tools.dip2px(getApplicationContext(), 10);
		ImageView image = (ImageView) v.findViewById(R.id.iv_picture);
		image.setImageBitmap(bitmap);
		ImageView trashcan = (ImageView) v.findViewById(R.id.iv_trashcan);
		trashcan.setOnClickListener(this);
		trashcan.setTag(mImgCapturePath);
		mPictureThumbLayout.addView(v, 0);
		mPhotoPaths.add(mImgCapturePath);
	}

	private void takePhoto() {
//		mPhotoPath = Tools.obtainDirPath(getApplicationContext(), Define.TMP_PICTURE_DIR) 
//				+ "/picture-" + System.currentTimeMillis() + ".jpg";
//		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//		intent.putExtra("scale", true);
//		intent.putExtra("noFaceDetection", true);
//		intent.putExtra(MediaStore.EXTRA_OUTPUT,
//				Uri.fromFile(new File(mPhotoPath)));
//		startActivityForResult(intent, Define.ACTIVITY_CODE_PICTURE_FROM_CAMERA);
		
		mImgCapturePath = mImgTempCachePath + "/capture-" + System.currentTimeMillis() + ".jpg";
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		intent.putExtra("scale", true);
		intent.putExtra("noFaceDetection", true);
		intent.putExtra(MediaStore.EXTRA_OUTPUT,
				Uri.fromFile(new File(mImgCapturePath)));
		startActivityForResult(intent, Define.ACTIVITY_CODE_PICTURE_FROM_CAMERA);
	}

	private void changeCheckStatus(View v) {
		if(mProductIds.contains(v.getTag())) {
			mProductIds.remove(v.getTag());
			((ImageView) v).setImageResource(R.drawable.ic_apply_exchange_unchecked);
		}else {
			mProductIds.add((Integer) v.getTag());
			((ImageView) v).setImageResource(R.drawable.ic_apply_exchange_checked);
		}
	}
	
	private void dismissProgressDialog() {
		if(mProgressDialog != null && mProgressDialog.isShowing()) {
			mProgressDialog.dismiss();
		}
	}
	
	private void initHandler() {
		mSubmitApplyExchangeListener = new SubmitApplyExchangeListener() {
			
			@Override
			public void onStart() {
				// TODO Auto-generated method stub
				if(mProgressDialog == null) {
					mProgressDialog = DialogUtils.showProgressDialog(
							ApplyExchange.this, null, "申请提交中, 请稍等", true, false, null);
				}else {
					mProgressDialog.show();
				}
			}
			
			@Override
			public void onResponseFailed() {
				// TODO Auto-generated method stub
				ToastUtils.showToast(ApplyExchange.this, "申请失败, 请重试");
				mCurrentQueuePosition = 0;
				dismissProgressDialog();
			}
			
			@Override
			public void onOffline() {
				// TODO Auto-generated method stub
				dismissProgressDialog();
				mOfflineDialog.show();
			}
			
			@Override
			public void onNoNetWork() {
				// TODO Auto-generated method stub
				ToastUtils.showToast(ApplyExchange.this, Define.MSG_NO_NETWORK);
				dismissProgressDialog();
			}
			
			@Override
			public void onResponseSuccess() {
				// TODO Auto-generated method stub
				dismissProgressDialog();
				ToastUtils.showToast(ApplyExchange.this, "申请成功");
				setResult(Define.ACTIVITY_CODE_APPLY_EXCHANGE);
				finish();
			}
		};
		
		mUploadApplyExchangePictureListener = new UploadApplyExchangePictureListener() {
			
			@Override
			public void onStart() {
				// TODO Auto-generated method stub
				if(mProgressDialog == null) {
					mProgressDialog = DialogUtils.showProgressDialog(
							ApplyExchange.this, null, "申请提交中, 请稍等", true, false, null);
				}else {
					mProgressDialog.show();
				}
			}
			
			@Override
			public void onResponseFailed() {
				// TODO Auto-generated method stub
				ToastUtils.showToast(ApplyExchange.this, "申请失败, 请重试");
				mCurrentQueuePosition = 0;
				dismissProgressDialog();
			}
			
			@Override
			public void onOffline() {
				// TODO Auto-generated method stub
				dismissProgressDialog();
				mOfflineDialog.show();
			}
			
			@Override
			public void onNoNetWork() {
				// TODO Auto-generated method stub
				ToastUtils.showToast(ApplyExchange.this, Define.MSG_NO_NETWORK);
				dismissProgressDialog();
			}
			
			@Override
			public void onResponseSuccess(int width, int height, String imageUrl,
					String uploadString) {
				// TODO Auto-generated method stub
				mSBuilder.append(uploadString + "|");
				mCurrentQueuePosition++;
				if(mCurrentQueuePosition < mPhotoPaths.size()) {
					ISmartMall.getInstance().uploadApplyExchangePicture(mPhotoPaths.get(mCurrentQueuePosition), this);
					
				}else {
					uploadContent();
				}
			}
		};
		
	}
	
	private void initProductItemLayout() {
		for(int i = 0; mOrderCommoditiesInfos != null && i < mOrderCommoditiesInfos.size(); i++) {
			View root = mInflater.inflate(R.layout.apply_exchange_product_item, null);
			
			ImageView icon = (ImageView) root.findViewById(R.id.iv_product);
			TextView price = (TextView) root.findViewById(R.id.tv_price);
			TextView num = (TextView) root.findViewById(R.id.tv_product_num);
			TextView intro = (TextView) root.findViewById(R.id.tv_product_name);
			ImageView check = (ImageView) root.findViewById(R.id.iv_check);
			check.setTag(mOrderCommoditiesInfos.get(i).getProductId());
			root.setOnClickListener(this);
			root.setTag(check);
//			check.setOnClickListener(this);
			if(i == mOrderCommoditiesInfos.size() - 1) {
				((RelativeLayout.LayoutParams) root.findViewById(R.id.divider).getLayoutParams()).leftMargin = 0;
			}
			
			price.setText("￥" + new DecimalFormat("0.00").format(mOrderCommoditiesInfos.get(i).getPrice()));
			num.setText("数量：" + mOrderCommoditiesInfos.get(i).getBuyNum());
			intro.setText(mOrderCommoditiesInfos.get(i).getProductTitle());
			ImageLoader.getInstance().displayImage(mOrderCommoditiesInfos.get(i).getProductPicture(), icon);
			mProductItemLayout.addView(root);
		
		}
	}
	
	private void submit() {
		if(mProductIds.size() < 1){
			ToastUtils.showToast(getApplicationContext(), "请勾选需要退换货的商品");
			
		}else if(TextUtils.isEmpty(mEtReason.getText().toString())) {
			ToastUtils.showToast(getApplicationContext(), "请输入退换货原因");
			
		}else if(mPhotoPaths.size() > 0) {
			uploadPicture();
			for(String path : mPhotoPaths) {
				CrashHandler.d(TAG, path);
			}
			
		}else {
			uploadContent();
		}
	}

	private void uploadContent() {
		try {
			ISmartMall.getInstance().submitApplyExchange(
					mOrderDetailInfo.getString("orderCode"), 
					mExchangeType, 
					getProductId(), 
					mEtReason.getText().toString(), 
					mSBuilder.length() == 0 ? "" : mSBuilder.substring(0, mSBuilder.length() - 1), 
					mSubmitApplyExchangeListener);
		
		}catch(JSONException e) {
			CrashHandler.e(e);
		}
	}
	
	private String getProductId() {
		StringBuilder sb = new StringBuilder();
		for(int productId : mProductIds) {
			sb.append(productId + "|");
		}
		return sb.toString();
	}
	
	private void uploadPicture() {
		// TODO Auto-generated method stub		
//			RequestParams params = new RequestParams();
//			params.put("image", new File(mPhotoPaths.get(mCurrentQueuePosition)));
//			SingtonAsyncHttpClient.getInstance().post(
//					Define.URL_MALL_APPLY_EXCHANGE_UPLOAD_PICTURE, 
//					params,
//					mAddPictureHttpHandler);
		ISmartMall.getInstance().uploadApplyExchangePicture(mPhotoPaths.get(mCurrentQueuePosition), mUploadApplyExchangePictureListener);
			
	}
	
}
